from selenium.webdriver.chrome.service import Service
from selenium import webdriver
from config.config import PROJECT_PATH
from os.path import join
from selenium.webdriver.common.by import By
def _service():
    s = Service(join(PROJECT_PATH, 'service','chromedriver.exe'))#加是将原本的\变得意义
    return s
def Chrome():
    driver = webdriver.Chrome(service=_service())
    driver.maximize_window()
    return driver

class Table:
    """这是一个处理表格的类"""
    def __init__(self, table_obj):
        self.table_obj = table_obj
    #传一个表格的元素对象
    # 定位器
    th_locator = (By.TAG_NAME, "th")
    tr_locator = (By.TAG_NAME, "tr")
    td_locator = (By.TAG_NAME, "td")
    def _raw(self,has_th=True):
        """内部调用函数，其中如果要用th则不传参，默认全部行，若不要th则has_th要传False"""
        trs = self.table_obj.find_elements(*self.tr_locator)
        if not trs:  # 处理空表格情况
            return []

        if has_th:
            return trs
        else:
            # 安全判断第一行是否有th（用find_elements避免报错）
            first_row_ths = trs[0].find_elements(*self.th_locator)
            if first_row_ths:  # 若第一行有th，则排除表头行
                return trs[1:] if len(trs) > 1 else []
            else:  # 若第一行没有th，则返回所有行
                return trs
    def get_table(self,row,col):
        """获取单元格的对象"""
        tr = self._raw(has_th=False)[row-1]
        td = tr.find_elements(*self.td_locator)[col-1]
        return td
    def get_row(self,row):
        """获取行中所有数据"""
        tr = self._raw(has_th=False)[row-1]
        return tr.text
    def get_col(self,col):
        """获取列的所有元素"""
        li=[]
        trs = self._raw(has_th=False)
        for tr in trs:
            td= tr.find_elements(*self.td_locator)
            li.append(td[col-1].text)
        return li
